extends Node2D
class_name VirtualJoysticks

signal sOnInput
@export var deadRadius = 2
@export var maxRadius = 10
@export var touchRadius = 10
var startPos:Vector2
var movePos:Vector2
var actualUIMovePos:Vector2
var started:bool = false
var ipt:Vector2 = Vector2.ZERO

@onready var circleArea = $Control/CircleArea
@onready var circleDeadArea = $Control/CircleDeadArea
@onready var circleTouchPos = $Control/CircleTouchPos
@onready var uiParent = $Control


func _ready():
	uiParent.modulate.a = 0.0


func _input(event):
	if event is InputEventMouseButton:
		if event.pressed:
			onPress(event.position)
		else:
			onRelease(event.position)
	elif event is InputEventMouseMotion:
		onMove(event.position)
	elif event is InputEventScreenTouch:
		if event.pressed:
			onPress(event.position)
		else:
			onRelease(event.position)
	elif event is InputEventScreenDrag:
		onMove(event.position)
		

func onPress(pos):
	started = true
	startPos = pos
	movePos = startPos
	ipt = Vector2.ZERO
	uiParent.modulate.a = 1.0
	

func onRelease(pos):
	started = false
	ipt = Vector2.ZERO
	uiParent.modulate.a = 0.0
	
	
func onMove(pos):
	movePos = pos
	

func _physics_process(delta):
	if started:
		calcVelocity()
	sOnInput.emit(ipt)
	
	if (movePos - startPos).length() > maxRadius:
		actualUIMovePos = startPos + (movePos - startPos).normalized() * maxRadius
	else:
		actualUIMovePos = movePos
	
	updateUI()


func calcVelocity():
	var dist = startPos.distance_to(movePos)
	if dist < deadRadius:
		ipt = Vector2.ZERO
	else:
		var ratio = (dist - deadRadius) * 1.0 / (maxRadius - deadRadius)
		ratio = clamp(ratio, 0.0, 1.0) * 1.0
		ipt = (movePos - startPos).normalized() * ratio
		
	
func updateUI():
	circleArea.setPos(startPos)
	circleArea.setRadius(maxRadius)
	
	circleDeadArea.setPos(startPos)
	circleDeadArea.setRadius(deadRadius)
	
	circleTouchPos.setPos(actualUIMovePos)
	circleTouchPos.setRadius(touchRadius)
	
